<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      title="选取打卡地址"
      :visible="positionDialog"
      :before-close="closePositionDialog"
      @close="closePositionDialog"
      append-to-body
      width="1000px"
    >
      <div class="content">
        <div class="search-box">
          <div class="label">关键字搜索</div>
          <el-input
            v-model="input"
            placeholder="请输入内容"
            id="tipinput"
          ></el-input>
        </div>
        <div ref="map" id="map-container"></div>
        <span>打卡范围 </span>
        <el-select v-model="position.range" style="margin-top: 20px" placeholder="请选择" clearable>
          <el-option
            v-for="item in rangeList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </div>

      <span slot="footer">
        <el-button @click="closePositionDialog" size="medium">取消</el-button>
        <el-button type="primary" @click="handlePositionDialog" size="medium">
          确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";

window._AMapSecurityConfig = {
  // 设置安全密钥
  securityJsCode: "1082b73c5629b945d1a4c0498a8fa7db",
};

export default {
  name:"clockPlace",
  props: {
    positionDialog: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      input: "",
      map: null,
      lnglat: [], //   [longitude,latitude]  经度和纬度
      auto: null,
      placeSearch: null,
      markers: [],
      position: {
        range:"1000",
      }, //传给父组件的值【放经纬度和地址】
      rangeList:[
        {
          label:"100米",
          value:"100",
        },{
          label:"200米",
          value:"200",
        },{
          label:"300米",
          value:"300",
        },{
          label:"400米",
          value:"400",
        },{
          label:"500米",
          value:"500",
        }
        ,{
          label:"600米",
          value:"600",
        }
        ,{
          label:"700米",
          value:"700",
        }
        ,{
          label:"800米",
          value:"800",
        },{
          label:"900米",
          value:"900",
        },{
          label:"1000米",
          value:"1000",
        },{
          label:"1500米",
          value:"1500",
        },{
          label:"2000米",
          value:"2000",
        },{
          label:"2500米",
          value:"2500",
        },{
          label:"3000米",
          value:"3000",
        }
      ],
    };
  },
  watch: {
    // 监听事件 如果打开了弹框才加载地图，否则不加载地图
    positionDialog(type) {
      if (type) {
        //type True or false
        this.initMap();
      }
    },
  },

  methods: {
    async initMap() {
      await this.$nextTick();
      console.log(this.$refs.map);
      AMapLoader.load({
        key: "ce4f6710c1023a7d535650c2df86c240", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.AutoComplete", "AMap.PlaceSearch", "AMap.Geocoder"],
      })
        .then((AMap) => {
          console.log(AMap);
          this.map = new AMap.Map("map-container", {
            // 设置地图容器id
            viewMode: "3D", //  是否为3D地图模式
            zoom: 16, // 初始化地图级别
            center: [118.740452, 32.023695], //中心点坐标
            resizeEnable: true,
          });
          // 关键字查询
          this.searchMap();
          // 监听鼠标点击事件
          this.map.on("click", this.clickMapHandler);
        })
        .catch((e) => {
          console.log(e);
        });
    },

    // 点击地图事件获取经纬度，并添加标记
    clickMapHandler(e) {
      this.lnglat = [e.lnglat.getLng(), e.lnglat.getLat()];
      this.setMarker(this.lnglat);
      console.log(e, "点击地图", this.lnglat);
      // 点击地图上的位置，根据经纬度转换成详细地址
      let geocoder = new AMap.Geocoder({});
      let that = this;
      geocoder.getAddress(this.lnglat, function(status, result) {
        console.log(status, result);
        if (status === "complete" && result.regeocode) {
          console.log(result.regeocode);
          that.address = result.regeocode.formattedAddress;
        } else {
          console.log("查询地址失败，请稍后再试");
        }
      });
      this.position = {
        longitude: e.lnglat.getLng(),
        latitude: e.lnglat.getLat(),
        address: that.address,
        range: that.position.range
      };
      this.input = that.address //把查询到的地址赋值到输入框
    },
    // 关键字查询
    searchMap() {
      // 搜索框自动完成类
      this.auto = new AMap.AutoComplete({
        input: "tipinput", // 使用联想输入的input的id
      });
      //构造地点查询类
      this.placeSearch = new AMap.PlaceSearch({
        map: this.map,
      });
      // 当选中某条搜索记录时触发
      this.auto.on("select", this.selectSite);
      console.log(this.selectSite, "select");
    },
    //当选中某条搜索记录时触发
    selectSite(e) {
      if (e.poi.location) {
        console.log("经纬度", e);
        this.lnglat = [e.poi.location.lng, e.poi.location.lat];
        this.placeSearch.setCity(e.poi.adcode);
        this.placeSearch.search(e.poi.name); //关键字查询
        let geocoder = new AMap.Geocoder({});
        let that = this;
        geocoder.getAddress(this.lnglat, function(status, result) {
          if (status === "complete" && result.regeocode) {
            that.province = result.regeocode.addressComponent.province;
            that.city = result.regeocode.addressComponent.city;
            //自己想要赋的值，根据自己的做修改
            that.$set(that.position, "address", e.poi.name);
            that.$set(
              that.position,
              "coordinate",
              e.poi.location.lng + "," + e.poi.location.lat
            ); //纬度，经度
            console.log(that.position, "地址");
          } else {
            console.log("查询地址失败，请稍后再试");
          }
        });
      } else {
        this.$message.error("查询地址失败，请重新输入地址");
      }
    },
    //  添加标记
    setMarker(lnglat) {
      this.removeMarker();
      console.log("位置", lnglat);
      let marker = new AMap.Marker({
        position: lnglat,
      });
      marker.setMap(this.map);
      this.markers.push(marker);
    },
    // 删除之前后的标记点
    removeMarker() {
      if (this.markers) {
        this.map.remove(this.markers);
      }
    },
    closePositionDialog() {
      this.input = "";
      this.position =  {
        range:"1000",
      },
      this.$emit("update:positionDialog", false);
    },
    handlePositionDialog() {
      if (!this.position.address){
        this.$message.error("请选择一个打卡地点")
        return
      }
      if (!this.position.range){
        this.$message.error("请选择打卡范围")
        return
      }
      this.$emit("selPosition", this.position); //把选择的位置传给父组件
      this.closePositionDialog();
    },
  },
};
</script>

<style lang="scss">
.search-box {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  height: 50px;
  .label {
    width: 100px;
  }
}

.content {
  position: relative;
}

#panel {
  position: absolute;
  top: 50px;
  right: 20px;
}

#map-container {
  overflow: hidden;
  width: 100%;
  height: 500px;
  margin: 0;
}

.amap-sug-result{
  visibility: visible;
  z-index: 99999 !important;
}

</style>

<style lang="scss" scoped>
::v-deep .amap-logo {
  display: none;
  opacity: 0 !important;
}
::v-deep .amap-copyright {
  opacity: 0;
}
</style>
